package 链表;

public class LC_019删除链表倒数第N个节点 {
    public static class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }
    public static void main(String[] args){
         ListNode head=new ListNode(1);
         head.next=new ListNode(2);
         head.next.next=new ListNode(3);
         head.next.next.next=new ListNode(4);
         head.next.next.next.next=new ListNode(5);
         int n=2;
         ListNode listnode=removeNthFromEnd(head,n);
         ListNode cur=listnode;
         while(cur!=null){
             System.out.print(cur.val+" ");
             cur=cur.next;
         }
    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyhead=new ListNode(-1,head);
        ListNode fast=dummyhead;
        ListNode slow=dummyhead;
        n++;
        while(n--!=0 && fast!=null)
            fast=fast.next;
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return dummyhead.next;
    }
    public static int getLength(ListNode head){
        ListNode cur=head;
        int length=0;
        while(cur!=null){
            length++;
            cur=cur.next;
        }
        return length;
    }
}
